package manage.action;

import m.common.action.ActionMeta;
import m.common.action.VuePageResult;
import m.common.action.VueResult;
import m.common.model.UserModel;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.html.VueListResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.other.DisplayItem;
import m.html.list.*;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import manage.model.ActionLog;
import manage.model.ActionLogUser;
import manage.model.OrgGroupView;
import manage.service.ActionLogService;

import java.util.Date;

@ActionMeta(name="manage/actionLog",title="Action日志")
public class ActionLogAction extends ManageAction{

    private ActionLog model;
    public JSONMessage record() throws MException {
        if(null==this.model) throw new MException(this.getClass(),"没有日志信息");
        ActionLog rlog=new ActionLog();
        rlog.setRequestIp(getRequest().getIpAddress());
        rlog.setUserAgent(getRequest().getHeader("User-Agent"));
        rlog.setCreateDate(new Date());
        rlog.setOid(GenerateID.generatePrimaryKey());
        rlog.setBusiness("C");
        rlog.setTitle(this.model.getTitle());//标题
        rlog.setDescription(this.model.getDescription());//描述
        rlog.setHost(getRequest().getHeader("host"));
        rlog.setPath(this.model.getPath());//路径
        UserModel model=getSessionLogUser();
        if(null!=model) {
            rlog.setUser(new ActionLogUser());
            rlog.getUser().setOid(model.getOid());
        }
        OrgGroupView dept=getSessionOrgGroup();
        if(null!=dept){
            rlog.setDept(dept);
        }
        rlog.setReadText(this.model.getReadText());//参数
        rlog.setBackText(this.model.getBackText());//返回
        rlog.setStatus(this.model.getStatus());//状态
        rlog.setProcessTime(0);
        ModelUpdateUtil.insertModel(rlog);
        return new JSONMessage(0);
    }
    public VueResult toView() throws Exception {
        if(ObjectUtil.notEmptyOid(model)){
            model= ModelQueryList.getModel(model,"*","user.*");
        }else{
            throw new MException(this.getClass(),"参数错误");
        }
        return new VuePageResult("page/base/host/viewActionLog.js")
                .addParam("model", model);
    }
    public JSONMessage doDelete30Before() throws Exception {
        systemLog("操作日志","删除30天前的操作日志");
        verifyAdminOperPower("manage_system_power");
        getService(ActionLogService.class).doDelete30Before();
        return new JSONMessage(0,"删除成功");
    }
    public JSONMessage doDelete() throws Exception {
        verifyAdminOperPower("manage_system_power");
        if(ObjectUtil.isEmptyOid(model)) throw new MException(this.getClass(),"没有要删除的记录");
        ModelUpdateUtil.deleteModel(model);
        return new JSONMessage(0,"删除成功");
    }
    /*
     * 操作日志列表
     */
    public VueResult logList() throws Exception {
        if(StringUtil.isSpace(getParamsValue("business"))) getParams().put("business","B");
        boolean power=hasAdminOperPower("manage_system_power");
        VueListResult result=getVueListResult("操作日志列表", ActionLog.class, actionUrl("logList"));
        result.hideTitle();
        result.setFieldTabs("business", DisplayItem.toList("manage.model.ActionLog!business"));
        result.setThreading(true);
        result.setFunction(true,true);
        result.setSelection("oid",false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("请求IP", "requestIp", 100, true));
        result.addCol(toTextColumn("客户端", "userAgent", 100, true));
        result.addCol(toTextColumn("主机", "host", 100, true));
        result.addCol(toTextColumn("路径", "path", 150, true));
        result.addCol(toTextColumn("用户类型", "user.userType", 100, true));
        result.addCol(toTextColumn("操作用户", "user.realname", 100, true));
        result.addCol(toTextColumn("所属部门", "dept.name", 130, true)
            .setFieldExpression("concat(#{dept.org.name},'/',#{dept.name})")
        );
        result.addCol(toDateTimeColumn("创建时间", "createDate", 130, true).setSort(ListSortOrder.DESC)
            .setLinkEvent(new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid"))
            .setType(ListColumnType.LINK)
        );
        result.addCol(toTextColumn("状态", "status", 100, true)
            .addElement(
                new ListElement("a-tag")
                    .addAttr(":color","decode(text,'正常','success','异常','error','错误','warning','processing')")
                    .addText("{{text}}")
            ).setAlign(Align.CENTER)
        );
        result.addCol(toTextColumn("标题", "title", 100, true));
        result.addCol(toTextColumn("描述", "description", 150, true));
        result.addCol(toTextColumn("接收数据", "readText", 200, true));
        result.addCol(toTextColumn("返回数据", "backText", 200, true));
        result.addCol(toIntegerColumn("处理时长", "processTime", 100, true));
        if(power) {
            result.addButton(ListButton.ajax("批量删除（30天前）", ButtonType.ERROR, actionUrl("doDelete30Before"), SuccessMethod.REFRESH)
                    .setConfirm("确定要删除30天前的操作日志吗?"));
            result.addButton(ListButton.ajax("批量删除", ButtonType.WARN, actionUrl("doDelete"), SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid").setConfirm("确定要删除吗?"));
        }
        //排序 result.addOrder
        //查询条件 result.addCondition
        return result;
    }

    public ActionLog getModel() {
        return model;
    }

    public void setModel(ActionLog model) {
        this.model = model;
    }
}
